import json
import numpy as np

def pearson_score(dataset,user1,user2):
    if user1 not in dataset:
        raise TypeError("User"+user1+'不在数据集中')
    if user2 not in dataset:
        raise TypeError("User"+user2+'不在数据集中')


    # 用户user1与user2共同参与评分的电影
    rated_by_both = {}
    for item in dataset[user1]:
        if item in dataset[user2]:
            rated_by_both[item]=1

    num_ratings = len(rated_by_both)
    # 如果没有共同评价过电影，分数为0
    if num_ratings == 0:
        return 0
    # 计算评分总和
    user1_sum = np.sum([dataset[user1][item] for item in rated_by_both])
    user2_sum = np.sum([dataset[user2][item] for item in rated_by_both])
    # 计算平方和
    user1_squared_sum = np.sum([np.square(dataset[user1][item]) for item in rated_by_both])
    user2_squared_sum = np.sum([np.square(dataset[user2][item]) for item in rated_by_both])
    # 计算乘积总和
    product_sum = np.sum([dataset[user1][item]*dataset[user2][item] for item in rated_by_both])
    # 计算皮尔逊相关系数
    Sxy = product_sum - (user1_sum*user2_sum / num_ratings)
    Sxx = user1_squared_sum - np.square(user1_sum)/num_ratings
    Syy = user2_squared_sum - np.square(user2_sum)/num_ratings
    if Sxx*Syy ==0:
        return 0
    # print(Sxy,Sxx,)
    # print(Syy)
    return Sxy / np.sqrt(Sxx*Syy)


if __name__ == '__main__':
    data_file = 'F:\python学习资料\Python-Machine-Learning-Cookbook-master\Chapter05\movie_ratings.json'
    with open(data_file,'r') as f:
        data = json.loads(f.read())

    user1 = 'John Carson'
    user2 = 'Michelle Peterson'

    print("相关系数:")
    print(pearson_score(data,user1,user2))